package com.example.blog_springboot.controller;

import com.example.blog_springboot.api.UserRest;
import com.example.blog_springboot.api.config.exception.NullException;
import com.example.blog_springboot.api.config.exception.RepeatException;
import com.example.blog_springboot.model.User;
import com.example.blog_springboot.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@RestController
public class UserController implements UserRest {
    @Resource
    private UserService userService;

    @Override
    public void login(String username, String password, HttpServletRequest request) throws Exception {
        if (StringUtils.isBlank(username) || StringUtils.isBlank(password)){
            throw new NullException();
        }
        userService.login(username,password,request);
    }

    @Override
    public void reg(String username, String password, HttpServletRequest request) throws Exception {
        userService.add(username,password);
        userService.login(username,password,request);
    }

    @Override
    public void logout(HttpServletRequest request) throws Exception {
        userService.logout(request);
    }

    @Override
    public User getUser(@SessionAttribute("user")User user) {
        return user;
    }

    @Override
    public User getWriter(String blogId,@SessionAttribute("user")User user) throws Exception {
        if (StringUtils.isBlank(blogId)){
            throw new Exception();
        }
        User writer = userService.getWriter(blogId,user);
        return writer;
    }
}